package org.jsola.hr.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.jsola.admin.vo.SiteListVO;
import org.jsola.common.DateKit;
import org.jsola.hr.common.DateUtils;
import org.jsola.hr.common.HrKit;
import org.jsola.hr.constant.DateType;
import org.jsola.hr.dao.IGregorianCalendarDAO;
import org.jsola.hr.dto.attendschedule.AttendJuHeAPIDTO;
import org.jsola.hr.dto.attendschedule.AttendJuHeHolidayDTO;
import org.jsola.hr.dto.attendschedule.AttendJuHeHolidayDetailDTO;
import org.jsola.hr.entity.GregorianCalendarDO;
import org.jsola.hr.provider.ISiteProviderService;
import org.jsola.hr.query.GregorianCalendarQuery;
import org.jsola.hr.service.IGregorianCalendarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

/**
 * 初始化次月考勤日历
 * @author zhr
 */
@Slf4j
@Component
public class AttendCalendarNextMonthTask {

    @Autowired
    private IGregorianCalendarDAO gregorianCalendarDAO;
    @Autowired
    private ISiteProviderService siteProviderService;
    @Autowired
    private IGregorianCalendarService gregorianCalendarService;

    /**
     * 每月最后一天23点执行一次
     */
     @Scheduled(cron = "0 59 23 28-31 * ?") // 每月最后一天23点执行一次
//    @Scheduled(cron = "00 47 14 * * ?") // 每天4点10分30秒触发
    public void initGregorianCalendar() {
        Date now = DateKit.getToday();

        // 下个月
        Date nextMonth =  DateUtils.getFirstDayOfNextMonth(DateKit.getDateStr(now));
//        Date nextMonth =  DateUtils.getFirstDayOfNextMonth("2020-5-31");
        String year = DateKit.getDateStr(nextMonth, "yyyy");
        String month = DateKit.getDateStr(nextMonth, "M");
        String monthWhole = DateKit.getDateStr(nextMonth, "MM");

        // 调用API接口获取当月的法定节假日
        String url = "http://v.juhe.cn/calendar/month?key=867ac20857946c53ed22df1346533101&year-month=" + year + "-" + month;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).method("GET",null).build();
        Call call = okHttpClient.newCall(request);
        String jsonData = "";
        try {
            Response response = call.execute();
            jsonData = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (StringUtils.isBlank(jsonData)) {
            log.info("聚合数据万年历接口返回空");
            return;
        }

        log.info("获取节假日信息---->" + jsonData);

        AttendJuHeAPIDTO attendJuHeAPIDTO = JSON.parseObject(jsonData, AttendJuHeAPIDTO.class);
        if(Objects.isNull(attendJuHeAPIDTO)){
            log.info("聚合数据万年历接口返回空");
            return;
        }

        List<AttendJuHeHolidayDetailDTO> attendJuHeHolidayDetailDTOList = new ArrayList<>();

        try {
            if(attendJuHeAPIDTO.getError_code().equals("0")){
                Map map = JSON.parseObject(attendJuHeAPIDTO.getResult(), Map.class);
                String dataStr = Objects.isNull(map.get("data")) ? "" : map.get("data").toString();
                if(StringUtils.isBlank(dataStr)){
                    log.info("近几个月无节假日列表");
                    return;
                }else{
                    Map hashMap = JSON.parseObject(dataStr, Map.class);
                    String holidayArrayStr = "";
                    if(Objects.isNull(hashMap)){
                        log.info("近几个月无节假日列表");
                        return;
                    }else{
                        holidayArrayStr = Objects.isNull(hashMap.get("holiday_array")) ? "" : hashMap.get("holiday_array").toString();
                    }
                    List<AttendJuHeHolidayDTO> attendJuHeHolidayDTOList = JSON.parseArray(holidayArrayStr.toString(), AttendJuHeHolidayDTO.class);
                    if(CollectionUtils.isEmpty(attendJuHeHolidayDTOList)){
                        log.info("近几个月无节假日列表");
                    }else{
                        attendJuHeHolidayDTOList.forEach(item -> {
                            if(DateKit.getFormatDate(DateKit.getDate("yyyy-MM-dd", item.getFestival()), "yyyy").equals(year)
                            && DateKit.getFormatDate(DateKit.getDate("yyyy-MM-dd", item.getFestival()), "M").equals(month)){
                                // 相同年月的节假日列表
                                attendJuHeHolidayDetailDTOList.addAll(item.getList());
                            }
                        });
                    }
                }
            }else{
                log.info("万年历接口返回异常，状态码：" + attendJuHeAPIDTO.getError_code());
                return;
            }
        } catch (Exception e) {
            log.info("解析错误...");
        }


        // 查询所有站点
        List<SiteListVO> siteList = siteProviderService.select();
        if (siteList == null || siteList.size() <= 0) {
            log.info("未查询到站点信息");
            return;
        }

        // 获取某个月有多少天
        Integer days = HrKit.getDaysOfMonth(nextMonth);

        for (int i = 1; i <= days; i++) {
            Boolean match = false;
            String dayStr = "";
            if (i < 10) {
                dayStr = "0" + i;
            }
            else {
                dayStr = i + "";
            }
            String dateStr = year + "-" + month + "-" + dayStr;
            String dateStrWhole = year + "-" + monthWhole + "-" + dayStr;

            // 1-工作日,2-休息日,3-法定节假日
            Integer dateType = DateType.WORK_DAY.getValue();

            if(!CollectionUtils.isEmpty(attendJuHeHolidayDetailDTOList)){
                for (AttendJuHeHolidayDetailDTO attendJuHeHolidayDetailDTO: attendJuHeHolidayDetailDTOList) {
                    if(dateStr.equals(attendJuHeHolidayDetailDTO.getDate())){
                        match = true;
                        if(attendJuHeHolidayDetailDTO.getStatus().equals("1")){
                            // 节假日
                            dateType = DateType.LEGAL_HOLIDAY.getValue();
                        }else if(attendJuHeHolidayDetailDTO.getStatus().equals("2")){
                            // 工作日
                            dateType = DateType.WORK_DAY.getValue();
                        }
                    }
                }
            }

            if(!match){
                continue;
            }

            // 工作日
            if (dateType == 1) {
                // 补班
            }

            for (SiteListVO site : siteList) {
                // 查询这个站点下，是否已经有了某年，某月某日的数据了
                GregorianCalendarQuery gregorianCalendarQuery = new GregorianCalendarQuery();
                gregorianCalendarQuery.setDateStr(dateStrWhole);
                List<GregorianCalendarDO> gregorianCalendarList = gregorianCalendarService.selectDO(gregorianCalendarQuery, site.getId());
                if (gregorianCalendarList.size() > 0) {
                    continue;
                }

                GregorianCalendarDO gregorianCalendarDO = new GregorianCalendarDO();

                gregorianCalendarDO.setId(UUID.randomUUID().toString().replace("-", ""));
                gregorianCalendarDO.setYearly(year);
                gregorianCalendarDO.setMonthly(monthWhole);
                gregorianCalendarDO.setDaily(dayStr);
                gregorianCalendarDO.setDateStr(dateStrWhole);
                gregorianCalendarDO.setDateType(dateType);
                gregorianCalendarDO.setCompanyId("");
                gregorianCalendarDO.setGmtCreate(new Date());
                gregorianCalendarDO.setGmtModified(new Date());
                gregorianCalendarDO.setCreateUserId("task");
                gregorianCalendarDO.setModifiedUserId("task");
                gregorianCalendarDO.setSiteId(site.getId());
                gregorianCalendarDO.setValid(true);

                gregorianCalendarDAO.insert(gregorianCalendarDO);
            }

        }
    }

    public static void main(String[] args) {

        Date now = DateKit.getToday();

        // 下个月
//        Date nextMonth =  DateUtils.getFirstDayOfNextMonth(DateKit.getDateStr(now));
        Date nextMonth =  DateUtils.getFirstDayOfNextMonth("2020-5-20");
        String year = DateKit.getDateStr(nextMonth, "yyyy");
        String month = DateKit.getDateStr(nextMonth, "M");

        // 调用API接口获取当月的法定节假日
        String url = "http://v.juhe.cn/calendar/month?key=867ac20857946c53ed22df1346533101&year-month=" + year + "-" + month;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).method("GET",null).build();
        Call call = okHttpClient.newCall(request);
        String jsonData = "";
        try {
            Response response = call.execute();
            jsonData = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (StringUtils.isBlank(jsonData)) {
            return;
        }

        JSONObject object = JSON.parseObject(jsonData);

        System.out.println(JSON.toJSONString(object));
    }

}
